/**
 * 存储数据并设置过期时间（例如，过期时间为 1 小时） expiration：过期时间
 * @param {*} key
 * @param {*} value
 * @param {*} expiration
 */
export const setWithExpiration = (key, value, expiration = 1) => {
	const expireTime = Date.now() + expiration * 60 * 60 * 1000; // 计算过期的时间戳（ms）
	const item = {
		value: value,
		expiration: expireTime,
	};
	uni.setStorageSync(key, item);
};

/**
 * 读取数据并检查过期
 * @param {*} key
 * @returns
 */
export const getWithExpiration = (key) => {
	const item = uni.getStorageSync(key);
	if (item && Date.now() < item.expiration) {
		return item.value; // 数据未过期，返回值
	} else {
		uni.removeStorageSync(key); // 数据过期或不存在，删除数据
		return null;
	}
};

/**
 *  清除过期数据
 * @param {*} reserve
 */
export const clearWithExpiration = (reserve = []) => {
	let keyList = [];
	if (Array.isArray(reserve) && reserve.length > 0) {
		keyList = reserve;
	}
	const res = uni.getStorageInfoSync();
	console.log("clearWithExpiration", res.keys);
	const clearKeys = res.keys.filter((key) => !keyList.includes(key));
	console.log("clearKeys", clearKeys);
	clearKeys.forEach((key) => {
		uni.removeStorageSync(key);
	});
};
